<?php

class AccountController extends ControllerModuleWhm
{
	public function actionIndex()
	{
		$whmaccountAddForm = new WhmAccountAddForm();
		$whmaccount = new WhmAccount();
		$now = time();
		
		$postData = app()->request->getPost('WhmAccountAddForm', null);
		if($postData){
			$whmaccountAddForm->attributes = $postData;
			$ret = false;
			$detail = $errors = null;
			if($ret = $whmaccount->checkAccountsLimit()){
				if($whmaccountAddForm->validate()){
					$whmaccount->attributes = $postData;
					if($whmaccount->reLoadCpanelAccounts(false)){
						$whmaccount->last_cp_update = $now;
						
						if($ret = $whmaccount->save(true)){
							app()->__Whatever__Log->recordWhmAction(SystemLog::WACC_ADD, $whmaccount->domain, $whmaccount->id_account);
							
							$detail = $postData;
							$detail['id_account'] = $whmaccount->getPrimaryKey();
							$whmaccount->reLoadCpanelAccounts();
							$whmaccount->reLoadFunctions();
							
							$supremeUserRoles = UserRole::model()->findAllByAttributes(array('supreme' => 1));
							foreach($supremeUserRoles as $supremeUserRole){
								$userRolePermAccount = new UserRolePermAccount();
								$userRolePermAccount->allow_or_deny = 1;
								$userRolePermAccount->id_account = $whmaccount->getPrimaryKey();
								$userRolePermAccount->id_user_role = $supremeUserRole->id_user_role;
								$userRolePermAccount->save();
							}
						}
					}
				}else{
					$errors = $whmaccountAddForm->getErrors();
				}
			}
			$errors = $whmaccount->getErrors();
			
			$this->_returnAjax(
				array(
					'result' => $ret,
					'detail' => $detail,
					'errors' => $errors
				)
			);
		}
		
		$this->render('index', array(
			'whmaccountAddForm' => $whmaccountAddForm,
			'whmaccountEditForm' => new WhmAccountEditForm(),
			'sort' => app()->request->getParam('WhmAccount_sort', 'username_sort'),
			'whmaccount' => $whmaccount
		));
	}
	
	public function actionSearch()
	{
		$CpanelAccountsSearchForm = new CpanelAccountsSearchForm();
		
		$this->render('search', array(
			'CpanelAccountsSearchForm' => $CpanelAccountsSearchForm
		));
	}
	
	public function actionDetail($id_account)
	{
		$id_account = app()->request->getParam('id_account', null);
		if($id_account){
			if(app()->request->isAjaxRequest){
				$account = $this->loadModelByPk($id_account, 'WhmAccount');
				$this->_returnAjax(
					$account->attributes
				);
			}
		}
	}

    
    public function actionReload()
    {
    	$now = time();
    	if(app()->request->isAjaxRequest){
    		$id_account = app()->request->getParam('id_account', null);
    		if($id_account){
    			$ret = false;
				$errors = null;
    			$whmaccount = $this->loadModelByPk($id_account, 'WhmAccount');
    			
    			if(!app()->user->hasAccountAccess($id_account)){
					$whmaccount->addError('Access', 'You do not have access to this account');
					$this->_returnAjax(array(
	            		'result' => false,
						'errors' => $whmaccount->getErrors()
					));
				}
    			
    			$ret = $whmaccount->reLoadCpanelAccounts();
    			$ret = $whmaccount->reLoadFunctions() && $ret;
    			
    			if($ret){
    				app()->__Whatever__Log->recordWhmAction(SystemLog::WACC_REFRESH, $whmaccount->domain, $whmaccount->id_account);
    			}
    			
    			if(!$ret){
					$errors = $whmaccount->getErrors();
				}
				
				$this->_returnAjax(array(
            		'result' => $ret,
					'errors' => $errors
				));
    		}
    	}
    }
	
	public function actionEdit()
    {
    	$now = time();
		if(app()->request->isAjaxRequest){
	        $postData = app()->request->getParam('WhmAccountEditForm', null);
	    	if($postData){
	    		$whmAccountEditForm = new WhmAccountEditForm();
	    		$whmAccountEditForm->attributes = $postData;
				$ret = false;
				$detail = $errors = null;
				$whmaccount = $this->loadModelByPk($postData['id_account'], 'WhmAccount');
				if(!app()->user->hasAccountAccess($postData['id_account'])){
					$whmaccount->addError('Access', 'You do not have access to this account');
					$this->_returnAjax(array(
	            		'result' => false,
						'errors' => $whmaccount->getErrors()
					));
				}
				
		    	if($whmAccountEditForm->validate()){
		    		if(empty($postData['accesshash'])){
	            		unset($postData['accesshash']);
	            		$whmaccount->EnAccessHash = false;
					}else{
	            		$whmaccount->secure = '';
					}
		    		if(empty($postData['pass'])){
	            		unset($postData['pass']);
	            		$whmaccount->EnPass = false;
					}else{
	            		$whmaccount->pass_secure = '';
					}
					
					$whmaccount->attributes = $postData;
					$doReload = $whmaccount->accountChiefInfoChanged();
					if($ret = $whmaccount->save()){
						app()->__Whatever__Log->recordWhmAction(SystemLog::WACC_EDIT, $whmaccount->domain, $whmaccount->id_account);
						
						$detail = $postData;
						$detail['id_account'] = $whmaccount->getPrimaryKey();
						if($doReload){
							$ret = $whmaccount->reLoadCpanelAccounts()
    							&& $whmaccount->reLoadFunctions();
						}
					}
					
					if(!$ret){
						$errors = $whmaccount->getErrors();
					}
				}else{
					$errors = $whmAccountEditForm->getErrors();
				}
				
            	$this->_returnAjax(array(
            		'result' => $ret,
					'detail' => $detail,
					'errors' => $errors
				));
			}
		}else{
			$user->save();	
			$this->render('edit', array(
				'user' => $user,
			)); 
		}
    }
    
	public function actionDelete()
	{
		if(app()->request->isAjaxRequest){
			$id_account = app()->request->getPost('id_account', null);
			if($id_account){
				$account = $this->loadModelByPk($id_account, 'WhmAccount');
				if(!app()->user->hasAccountAccess($id_account)){
					$account->addError('Access', 'You do not have access to this account');
					$this->_returnAjax(array(
	            		'result' => false,
						'errors' => $account->getErrors()
					));
				}
				
				$ret = $account->delete();
				if($ret){
					app()->__Whatever__Log->recordWhmAction(SystemLog::WACC_DELETE, $account->domain, $account->id_account);
				}
				$this->_returnAjax(array(
					'result' => $ret,
					'errors' => $account->getErrors()
				));
			}
		
			$this->_end();
		}
	}
	
	public function actionLogin()
	{
		$this->layout = '//layouts/empty';
		$id_account = app()->request->getParam('id_account', null);
		if($id_account){
			if(!app()->user->hasAccountAccess($id_account)){
				$this->redirect(url('default/noaccess'));
			}
			
			$whmaccount = $this->loadModelByPk($id_account, 'WhmAccount');
			$whmApi = new WhmApi($whmaccount);
			app()->__Whatever__Log->recordWhmAction(SystemLog::WACC_DIRLOGIN, $whmaccount->domain, $whmaccount->id_account);
//			$whmApi->AccountLogin();
			$this->render('login', array(
				'whmApi' => $whmApi
			));
		}
//		$this->_end();
	}
	
	public function actionAuth()
	{
		$whmaccountAddForm = new WhmAccountAddForm();
		
		$postData = app()->request->getPost('WhmAccountAddForm', null);
		if($postData){
			$whmaccountAddForm->attributes = $postData;
			$ret = false;
			$errors = null;
			if($whmaccountAddForm->validate()){
				$whmaccount = new WhmAccount();
				$whmaccount->attributes = $postData;
				$whmApi = new WhmApi($whmaccount);
				$ret = $whmApi->AccountAuthByHash();
				if(!$ret){
					$errors = $whmApi->getErrors();
				}
			}else{
				$errors = $whmaccountAddForm->getErrors();
			}
			
			$this->_returnAjax(
				array(
					'result' => $ret,
					'errors' => $errors
				)
			);
		}		
	}
	
	public function actionReboot()
	{
		if(app()->request->isAjaxRequest){
			$id_account = app()->request->getPost('id_account', null);
			$forceful = app()->request->getPost('forceful', 0);
			$ret = false;
			$errors = null;
			
			$whmaccount = $this->loadModelByPk($id_account, 'WhmAccount');
			
			if(!app()->user->hasAccountAccess($id_account)){
				$whmaccount->addError('Access', 'You do not have access to this account');
				$this->_returnAjax(array(
            		'result' => false,
					'errors' => $whmaccount->getErrors()
				));
			}
			
			$whmApi = new WhmApi($whmaccount);
			if($whmApi->AccountAuthByHash()){
				$ret = $whmApi->reboot($forceful);
			}
			
			if(!$ret){
				$errors = $whmApi->getErrors();
			}else{
				app()->__Whatever__Log->recordWhmAction(($forceful == 0)? SystemLog::REB_GRA : SystemLog::REB_FORCE, $whmaccount->domain, $whmaccount->id_account);
			}
			
			$this->_returnAjax(array(
				'result' => $ret,
				'errors' => $errors
			));
		}
		
		$accounts = app()->request->getParam('accounts', null);
		$renderData = array(
			'accountsDataSource' => array(),
			'accountsCount' => 0,
			'denyRebootAccounts' => null
		);
		if(!empty($accounts['checked'])){
			$renderData['accountsDataSource'] = CHtml::listData(WhmAccount::model()->findAllByPk($accounts['checked']), 'id_account', 'domain');
			$renderData['accountsCount'] = WhmAccount::model()->countByAttributes(array('id_account' => $accounts['checked']));
			$whmaccounts = WhmAccount::model()->findAllByPk($accounts['checked']);
			$denyRebootAccounts = array();
			foreach($whmaccounts as $account){
				if(empty($account->AccountFunctions) || $account->AccountFunctions->reboot != 1){
					$denyRebootAccounts[] = $account;
				}
			}
			$renderData['denyRebootAccounts'] = $denyRebootAccounts;
		}
		
		$this->render('reboot', $renderData);
	}
	
	public function actionRestart()
	{
		$now = time();
		if(app()->request->isAjaxRequest){
			$id_account = app()->request->getPost('id_account', null);
			$services = app()->request->getPost('services', null);
			$ret = false;
			$restart = $errors = null;
			
			$whmaccount = $this->loadModelByPk($id_account, 'WhmAccount');
			
			if(!app()->user->hasAccountAccess($id_account)){
				$whmaccount->addError('Access', 'You do not have access to this account');
				$this->_returnAjax(array(
            		'result' => false,
					'errors' => $whmaccount->getErrors(),
					'time' => $now
				));
			}
			
			$whmApi = new WhmApi($whmaccount);
			if($ret = $whmApi->AccountAuthByHash()){
				foreach($services as $service){
					$restart[$service] = $whmApi->restart($service);
					if($restart[$service] === false){
						$restart[$service]['rawout'] = $restart[$service]['servicename'] = $whmApi->getLastError('Restart');
					}else{
						app()->__Whatever__Log->recordRestartAction($service, '', $whmaccount->id_account);
					}
				}
			}
			
			if(!$ret){
				$errors = $whmApi->getErrors();
			}

			$this->_returnAjax(array(
				'result' => $ret,
				'errors' => $errors,
				'restart' => $restart,
				'time' => $now
			));
		}
		
		$accounts = app()->request->getParam('accounts', null);
		$renderData = array(
			'accountsDataSource' => array(),
			'accountsCount' => 0,
			'denyRestartAccounts' => null
		);
		if(!empty($accounts['checked'])){
			$renderData['accountsDataSource'] = CHtml::listData(WhmAccount::model()->findAllByPk($accounts['checked']), 'id_account', 'domain');
			$renderData['accountsCount'] = WhmAccount::model()->countByAttributes(array('id_account' => $accounts['checked']));
			$whmaccounts = WhmAccount::model()->findAllByPk($accounts['checked']);
			$denyRestartAccounts = array();
			foreach($whmaccounts as $account){
				if(empty($account->AccountFunctions) || $account->AccountFunctions->restartservice != 1){
					$denyRestartAccounts[] = $account;
				}
			}
			$renderData['denyRestartAccounts'] = $denyRestartAccounts;
		}
		
		$this->render('restart', $renderData);
	}
	
	public function actionToolbox()
	{
		$now = time();
		if(app()->request->isAjaxRequest){
			
		}
		
		$accounts = app()->request->getParam('accounts', null);
		$renderData = array(
			'accountsDataSource' => array(),
			'accountsCount' => 0,
		);
		if(!empty($accounts['checked'])){
			$renderData['accountsDataSource'] = CHtml::listData(WhmAccount::model()->findAllByPk($accounts['checked']), 'id_account', 'domain');
			$renderData['accountsCount'] = WhmAccount::model()->countByAttributes(array('id_account' => $accounts['checked']));
		}
		
		$this->render('toolbox', $renderData);
	}
	
	public function actionIndividual()
	{
		$id_account = app()->request->getParam('id_account', null);
		$whmaccount = WhmAccount::model()->findByPk($id_account);
		$whmApi = new WhmApi($whmaccount);
		$whmApi->AccountAuthByHash();

		$SshSetupForm = new SshSetupForm();
		if($whmaccount->SshSetup){
			$SshSetupForm->attributes = $whmaccount->SshSetup->attributes;
		}
//		if(empty($SshSetupForm->public_key)){
//			$SshSetupForm->genSshpublicKey();
//		}
		
		$this->render('individual', array(
			'whmaccount' => $whmaccount,
			'whmApi' => $whmApi,
			'SshSetupForm' => $SshSetupForm
		));
	}
	
	public function actionSshSetup()
	{
		$postData = app()->request->getPost('SshSetupForm', null);
		if($postData){
			$SshSetupForm = new SshSetupForm();
			$SshSetupForm->attributes = $postData;
			$result = false;
			$errors = null;
			
			if($SshSetupForm->validate()){
				$result = $SshSetupForm->setup();
				if($result){
					
				}
			}
			if(!$result){
				$errors = $SshSetupForm->getErrors();
			}
			
			$this->_returnAjax(array(
				'result' => $result,
				'errors' => $errors
			));
		}
	}
	
	public function accessRules()
	{
		return array(
			array(
				'allow',
				'actions' => array('index', 'search', 'detail', 'reload', 'edit', 'delete', 'auth', 'reboot', 'restart', 'toolbox', 'individual', 'sshsetup', 'login'),
				'expression' => 'app()->user->isLogin() && app()->user->hasManageAccountPerm()',
				'redirect' => array('default/noaccess')
			),

			array(
				'deny',	//should be 'deny', 'allow' is used to give convenient to make test
				'users' => array('*'),
				'redirect' => array('user/login')
			)
		);
	}
}